import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { LowcodeDatasourceApi } from '#/api/lowcode/datasource';

import { z } from '#/adapter/form';
import { getSupportedDatabaseTypes } from '#/api/lowcode/datasource';
import { $t } from '#/locales';
import { DICT_TYPE, getDictOptions } from '#/utils';

/** 数据库类型对应的默认端口和驱动 */
const DB_TYPE_CONFIG = {
  mysql: {
    port: '3306',
    driver: 'com.mysql.cj.jdbc.Driver',
    urlTemplate: 'jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai',
    testQuery: 'SELECT 1',
  },
  postgresql: {
    port: '5432',
    driver: 'org.postgresql.Driver',
    urlTemplate: 'jdbc:postgresql://localhost:5432/database',
    testQuery: 'SELECT 1',
  },
  oracle: {
    port: '1521',
    driver: 'oracle.jdbc.OracleDriver',
    urlTemplate: 'jdbc:oracle:thin:@localhost:1521:orcl',
    testQuery: 'SELECT 1 FROM DUAL',
  },
  sqlserver: {
    port: '1433',
    driver: 'com.microsoft.sqlserver.jdbc.SQLServerDriver',
    urlTemplate: 'jdbc:sqlserver://localhost:1433;databaseName=database',
    testQuery: 'SELECT 1',
  },
  h2: {
    port: '9092',
    driver: 'org.h2.Driver',
    urlTemplate: 'jdbc:h2:mem:testdb',
    testQuery: 'SELECT 1',
  },
};

/** 新增/修改数据源的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'id',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'name',
      label: '数据源名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入数据源名称',
        maxlength: 50,
      },
      rules: z.string().min(1, '数据源名称不能为空').max(50, '数据源名称不能超过50个字符'),
    },
    {
      fieldName: 'type',
      label: '数据库类型',
      component: 'ApiSelect',
      componentProps: {
        api: async () => {
          const types = await getSupportedDatabaseTypes();
          return types.map(type => ({
            label: type.toUpperCase(),
            value: type,
          }));
        },
        placeholder: '请选择数据库类型',
      },
      rules: z.string().min(1, '请选择数据库类型'),
    },
    {
      fieldName: 'url',
      label: '数据库URL',
      component: 'Input',
      componentProps: {
        placeholder: '请输入数据库连接URL',
      },
      rules: z.string().min(1, 'JDBC URL不能为空'),
      help: 'JDBC连接字符串，如：jdbc:mysql://localhost:3306/database',
    },
    {
      fieldName: 'username',
      label: '用户名',
      component: 'Input',
      componentProps: {
        placeholder: '请输入数据库用户名',
        maxlength: 100,
      },
      rules: z.string().min(1, '用户名不能为空').max(100, '用户名不能超过100个字符'),
    },
    {
      fieldName: 'password',
      label: '密码',
      component: 'InputPassword',
      componentProps: {
        placeholder: '请输入数据库密码',
        maxlength: 100,
        autoComplete: 'new-password',
      },
      rules: z.string().max(100, '密码不能超过100个字符').optional(),
    },
    {
      fieldName: 'driverClassName',
      label: '驱动类名',
      component: 'Input',
      componentProps: {
        placeholder: '请输入JDBC驱动类名',
      },
      rules: z.string().min(1, '驱动类名不能为空'),
      help: 'JDBC驱动类的全限定名',
    },
    // 连接池配置
    {
      fieldName: 'initialSize',
      label: '初始连接数',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        max: 100,
        placeholder: '初始连接数',
        controlsPosition: 'right',
      },
      rules: z.number().min(0, '初始连接数不能小于0').max(100, '初始连接数不能大于100').optional(),
      defaultValue: 1,
    },
    {
      fieldName: 'minIdle',
      label: '最小空闲连接',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        max: 100,
        placeholder: '最小空闲连接数',
        controlsPosition: 'right',
      },
      rules: z.number().min(0, '最小空闲连接数不能小于0').max(100, '最小空闲连接数不能大于100').optional(),
      defaultValue: 1,
    },
    {
      fieldName: 'maxActive',
      label: '最大连接数',
      component: 'InputNumber',
      componentProps: {
        min: 1,
        max: 1000,
        placeholder: '最大连接数',
        controlsPosition: 'right',
      },
      rules: z.number().min(1, '最大连接数不能小于1').max(1000, '最大连接数不能大于1000').optional(),
      defaultValue: 8,
    },
    {
      fieldName: 'testQuery',
      label: '测试查询语句',
      component: 'Input',
      componentProps: {
        placeholder: '请输入测试查询语句',
      },
      rules: z.string().optional(),
      help: '用于测试连接的SQL语句，如：SELECT 1',
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'RadioGroup',
      componentProps: {
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
        buttonStyle: 'solid',
        optionType: 'button',
      },
      rules: z.number().default(0),
      defaultValue: 0,
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(handleStatusChange?: (newStatus: number, row: LowcodeDatasourceApi.DatasourceConfig) => Promise<boolean | undefined>): VxeTableGridOptions<LowcodeDatasourceApi.DatasourceConfig>['columns'] {
  return [
    {
      type: 'checkbox',
      width: 60,
    },
    {
      field: 'id',
      title: 'ID',
      width: 80,
    },
    {
      field: 'name',
      title: '数据源名称',
      minWidth: 120,
    },
    {
      field: 'type',
      title: '数据库类型',
      width: 100,
    },
    {
      field: 'url',
      title: '连接URL',
      minWidth: 200,
      showOverflow: 'tooltip',
    },
    {
      field: 'username',
      title: '用户名',
      width: 100,
    },
    {
      field: 'maxActive',
      title: '最大连接数',
      width: 100,
      align: 'center',
    },
    {
      field: 'status',
      title: '状态',
      width: 100,
      align: 'center',
      cellRender: {
        name: 'CellSwitch',
        props: {
          disabled: !handleStatusChange,
          type: DICT_TYPE.COMMON_STATUS,
          onChange: handleStatusChange,
        },
      },
    },
    {
      field: 'createTime',
      title: '创建时间',
      width: 180,
      formatter: 'formatDateTime',
    },
    {
      title: '操作',
      width: 200,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}

/** 搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'name',
      label: '数据源名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入数据源名称',
      },
    },
    {
      fieldName: 'type',
      label: '数据库类型',
      component: 'Select',
      componentProps: {
        placeholder: '请选择数据库类型',
        options: [
          { label: 'MySQL', value: 'mysql' },
          { label: 'PostgreSQL', value: 'postgresql' },
          { label: 'Oracle', value: 'oracle' },
          { label: 'SQL Server', value: 'sqlserver' },
          { label: 'H2', value: 'h2' },
        ],
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      componentProps: {
        placeholder: '请选择状态',
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
      },
    },
  ];
}

/** 获取数据库类型配置 */
export function getDbTypeConfig(type: string) {
  return DB_TYPE_CONFIG[type] || DB_TYPE_CONFIG.mysql;
}